package io.renren.modules.sys.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.oss.cloud.OSSFactory;
import io.renren.modules.sys.entity.Classify;
import io.renren.modules.sys.service.ClassifyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/sys/classify")
@Api(tags = "多级分类管理接口")
public class ClassifyController extends AbstractController {

    @Resource
    private ClassifyService classifyService;

    @GetMapping("/list")
    @ApiOperation(value = "获取所有分类")
    public R listClassify(){
        List<Classify> classifyList = classifyService.list();
        return R.ok().put("data",classifyList);
    }

    @GetMapping("/listTree")
    @ApiOperation(value = "获取分类树")
    public R listWithTree(){
        List<Classify> classifyTreeList = classifyService.getAllParentClassify();
        return R.ok().put("data",classifyTreeList);
    }

    @GetMapping("/tree")
    @ApiOperation(value = "模糊查询获取分类树")
    public R listTree(@RequestParam Map<String,Object> params){
        String industryName = String.valueOf(params.get("industryName"));
        int depth = Integer.valueOf(String.valueOf(params.get("depth")));
        List<Classify> classifyTreeList = classifyService.queryClassifyAll(industryName,depth);
        return R.ok().put("data",classifyTreeList);
    }

    @PostMapping("/save")
    @ApiOperation(value = "添加行业分类")
    public R saveClassify(@RequestBody Classify classify){
        boolean result = classifyService.addClassify(classify);
        if (result){
            return R.ok().put("msg","添加行业分类成功");
        }else {
            return R.error("添加行业分类失败");
        }
    }

    @PostMapping("/modify")
    @ApiOperation(value = "修改行业分类")
    public R modifyClassify(@RequestBody Classify classify){
        boolean result = classifyService.updateClassify(classify);
        if (result){
            return R.ok().put("msg","修改行业分类成功");
        }else {
            return R.error("修改行业分类失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除行业分类")
    public R deleteClassify(@PathVariable("id")int id){
        boolean result = classifyService.deleteOne(id);
        if (result){
            return R.ok().put("msg","删除行业分类成功");
        }else {
            return R.error("删除行业分类失败");
        }
    }

    @DeleteMapping("/deleteBatch/{ids[]}")
    @ApiOperation(value = "批量删除行业分类")
    public R deleteBatchClassify(@PathVariable("ids[]")ArrayList<Integer> idList){
        boolean result = classifyService.deleteBatch(idList);
        if (result){
            return R.ok().put("msg","删除行业分类成功");
        }else {
            return R.error("删除行业分类失败");
        }
    }

    @GetMapping("/searchByPid/{pid}")
    @ApiOperation(value = "通过父类编号查询所有分类")
    public R getClassifyByPid(@PathVariable("pid")int pid){
        List<Classify> classifyList = classifyService.getClassifyByPid(pid);
        return R.ok().put("data",classifyList);
    }

    @PutMapping("/modifyIconPath")
    @ApiOperation(value = "修改行业图标地址")
    public R modifyIconPath(int id,String iconPath){
        boolean result = classifyService.updateIconPath(id,iconPath);
        if (result){
            return R.ok().put("msg","修改行业图标地址成功");
        }else {
            return R.error("修改行业图标地址失败");
        }
    }

    @PutMapping("/modifyIsHot")
    @ApiOperation(value = "修改行业热门推荐")
    public R modifyIsHot(int id,int isHot){
        boolean result = classifyService.updateHotRecommend(id,isHot);
        if (result){
            return R.ok().put("msg","修改行业热门推荐成功");
        }else {
            return R.error("修改行业热门推荐失败");
        }
    }

    @GetMapping("/search/{id}")
    @ApiOperation(value = "根据id查找分类")
    public R getClassifyById(@PathVariable(value = "id") int id){
        return R.ok().put("data",classifyService.getClassifyById(id));
    }



    @Value("${web.upload-path}")
    private String savePath;
    @Value("${web.relative-path}")
    private String relativePath;

    @PostMapping("/uploadFile")
    @ApiOperation(value = "图片上传")
    public String uploadFile(@RequestParam("file") MultipartFile multipartFile){
        if (multipartFile == null || multipartFile.getSize()==0){
            return "你未选择任何文件";
        }

        //文件保存目录
        File saveDir = new File(savePath);

        //判断目录是否存在，不存在则插件，如创建失败，则抛出异常
        if (!saveDir.exists()){
            saveDir.mkdirs();
        }

        //获取客户端上传文件名
        String fileName = multipartFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String finalName = UUID.randomUUID().toString().replace("-","")+suffix;
        File dest = new File(saveDir,fileName);
        try {
            multipartFile.transferTo(dest);
            String relative = relativePath+finalName;
            return relative;
        }catch (IOException e){
            return "上传图片失败";
        }
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

        url = "https://xun-xunbao.oss-cn-shanghai.aliyuncs.com/" + url;
        return R.ok().put("url",url);
    }
}
